<?php


require_once 'Objects/Token.php';

/**
 * This class represents a single user in the system.
 * By default, this is the "guest" user.
 */
class User {
	private $id = 0;				// ID.
	private $username;				// Username.
	private $password;				// MD5 Hash of the user's password.
	private $authorized = false;	// Indicates if the username and password are valid.

	/**
	 * Returns the ID of the current user
	 * 
	 * @return ID of the user.
	 */
	public function getID() {
		return $this->id;
	}

	/**
	 * Returns the username of the current user.
	 * 
	 * @return Username of the user.
	 */
	public function getUsername() {
		return $this->username;
	}
	
	/**
	 * Indicates if the user is authorized by checking the username and password.
	 * 
	 * @return True if the user is authorized, False otherwise.
	 */
	public function isAuthorized() {
		// If current "authorized" is null, we have to check it ourselves:
		if ($this->authorized === null) {
			if (($this->username != "") && ($this->password != "")) {
				// Check if authorized:
				$this->authorized = UserTable::isAuthorized($this->username, $this->password);
			} else {
				$this->authorized = false;
			}
		}
		
		// Return result:
		return $this->authorized;
	}
	
	
	/**
	 * Sets the ID for this user.
	 * 
	 * @param id The new ID.
	 */
	public function setID($id) {
		$this->authorized = null;
		$this->id = $id;
	}

	/**
	 * Sets the username for this user.
	 * 
	 * @param username The new username.
	 */
	public function setUsername($username) {
		$this->authorized = null;
		$this->username = $username;
	}

	/**
	 * Sets a new password for the user.
	 * 
	 * @param password MD5 representation of the password.
	 */
	public function setPassword($password) {
		$this->authorized = null;
		$this->password = $password;
	}
	
	/**
	 * Toggles the authorized attribute.
	 * 	True: User is marked as authorized (danger!).
	 * 	False: User is marked as unauthorized.
	 * 	Null: Authorize user automatically when needed.
	 * 
	 * @param authorized See above.
	 */
	public function setAuthorized($authorized) {
		$this->authorized = $authorized;
	}

	/**
	 * Gets the token object for this user and the given IP address if it exists.
	 * 	The IP Address should be a string.
	 * 
	 * @param ipAddress IP address of the user.
	 * @return A token object or NULL if not found.
	 */
	public function getToken($ipAddress) {
		return TokenTable::get($this->getID(), $ipAddress);
	}
	
	/**
	 * Checks if the given password is correct for this user.
	 * 	Make sure to check if the user is authorized aswell.
	 * 
	 * @param password Password to check.
	 */
	public function checkPassword($password) {
		// COnvert to MD5 and check:
		if(md5($password) == $this->password) {
			return true;
		} else {
			return false;
		}
	}

}
?>
